import React, { useState, useEffect, useContext } from "react";
import { Modal, Form, Input, InputNumber, Select, Button } from "antd";
import MarkdownIt from "markdown-it";
import { useTranslation } from "react-i18next";
import { MessageContext } from "../../App";
import {
  generateAIContent,
  createContent,
  type CreateContentRequest,
} from "../../services/apiService";

const { TextArea } = Input;

interface SaveContentModalProps {
  visible: boolean;
  htmlContent: string;
  onCancel: () => void;
  onSuccess: (productId: string) => void;
}

const SaveContentModal: React.FC<SaveContentModalProps> = ({
  visible,
  htmlContent,
  onCancel,
  onSuccess,
}) => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [aiGenerating, setAiGenerating] = useState(false);
  const message = useContext(MessageContext);

  // 当弹窗打开时自动提取内容
  useEffect(() => {
    if (visible && htmlContent) {
      const dailyContent = extractDailyContentToMarkdown(htmlContent);
      // 设置到表单的 content 字段
      form.setFieldsValue({
        content: dailyContent,
      });
    }
  }, [visible, htmlContent, form]);

  // AI 分析 HTML 内容生成所有表单数据
  const generateContentWithAI = async () => {
    setAiGenerating(true);
    try {
      // 先提取基础内容
      const basicContent = extractDailyContentToMarkdown(htmlContent);

      // 调用AI模型进行智能分析，生成完整的表单数据
      const aiResult = await generateAIContent({
        prompt: t('saveContentModal.aiPrompt', { content: basicContent }),
      });
      let aiResponseText = aiResult.response;

      // 移除<think>标签及其内容
      aiResponseText = aiResponseText.replace(/<think>[\s\S]*?<\/think>/g, "");

      // 尝试解析JSON响应
      let parsedData;
      try {
        // 提取JSON部分（去除可能的前后文本）
        const jsonMatch = aiResponseText.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          parsedData = JSON.parse(jsonMatch[0]);
        } else {
        throw new Error(t('saveContentModal.jsonNotFound'));
      }
    } catch (parseError) {
      console.error("JSON解析失败:", parseError);
      throw new Error(t('saveContentModal.aiDataFormatError'));
    }      // 设置表单字段（攻略内容保持原样，不使用AI生成的内容）
      form.setFieldsValue({
        city: parsedData.city || "",
        title: parsedData.title || "",
        content: basicContent, // 保持原本提取的内容
        durationDays: parsedData.durationDays || 1,
        tags: parsedData.tags || [],
      });

      message.success(t('saveContentModal.aiAnalysisCompleted'));
    } catch (error) {
      console.error("AI智能分析失败:", error);

      // 如果AI失败，回退到基础提取
      const fallbackContent = extractDailyContentToMarkdown(htmlContent);
      form.setFieldsValue({
        content: fallbackContent,
      });

      message.warning(t('saveContentModal.aiAnalysisFailed'));
    } finally {
      setAiGenerating(false);
    }
  };

  // 简化内容格式，减少字符数
  const simplifyContent = (content: string, dayNum: number): string => {
    try {
      // 提取标题（去掉emoji和多余信息）
      const titleMatch = content.match(/# 第(\d+)天([^\n]*)/);
      let simplifiedTitle = `Day ${dayNum}`;
      if (titleMatch) {
        // 提取关键地点信息 - 修复正则表达式
        const titleText = titleMatch[2];
        const locations = [];

        // 匹配常见地点名称
        const placePatterns = [
          "曼谷素万那普机场",
          "曼谷",
          "成都天府国际机场",
          "成都",
          "四姑娘山",
          "九寨沟",
          "宽窄巷子",
          "锦里",
          "春熙路",
        ];

        for (const place of placePatterns) {
          if (titleText.includes(place)) {
            locations.push(place.replace("机场", "").replace("国际", ""));
          }
        }

        // 去重并保持顺序
        const uniqueLocations = [...new Set(locations)];
        if (uniqueLocations.length > 0) {
          simplifiedTitle += `: ${uniqueLocations.join("→")}`;
        }
      }

      // 提取交通表格核心信息
      const tablePattern =
        /\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|/g;
      const routes = [];
      let match;
      let rowCount = 0;

      while ((match = tablePattern.exec(content)) !== null) {
        rowCount++;
        const cells = match.slice(1, 7).map((cell) => cell.trim());

        // 跳过表头行和分隔符行
        if (
          rowCount === 1 ||
          cells[0].includes("出发地") ||
          cells[0].includes("---") ||
          cells[0].includes(":--")
        ) {
          continue;
        }

        if (cells.length >= 6) {
          let from = cells[0]
            .replace(/酒店|机场|国际/g, "")
            .replace(/素万那普/g, "")
            .trim();
          let to = cells[1]
            .replace(/酒店|机场|国际/g, "")
            .replace(/素万那普/g, "")
            .trim();
          const method = cells[2].trim();
          const duration = cells[3].trim();
          const startTime = cells[4].trim();
          const endTime = cells[5].trim();

          // 简化地点名称
          from = from
            .replace("曼谷素万那普", "曼谷")
            .replace("成都天府", "成都");
          to = to.replace("曼谷素万那普", "曼谷").replace("成都天府", "成都");

          // 简化交通方式
          let simpleMethod = method;
          if (method.includes("飞机")) simpleMethod = "飞机";
          else if (method.includes("出租车") || method.includes("网约车"))
            simpleMethod = "车";
          else if (method.includes("步行")) simpleMethod = "步行";
          else if (method.includes("包车") || method.includes("大巴"))
            simpleMethod = "车";

          // 确保不是空值或无效数据
          if (
            from &&
            to &&
            from !== to &&
            duration &&
            !from.includes("-") &&
            !to.includes("-")
          ) {
            routes.push(
              `${from}→${to}(${simpleMethod},${duration},${startTime}-${endTime})`,
            );
          }
        }
      }

      let transportInfo = "";
      if (routes.length > 0) {
        transportInfo = `\n交通: ${routes.join(", ")}`;
      }

      const result = simplifiedTitle + transportInfo;
      return result;
    } catch (error) {
      console.error(`简化第${dayNum}天内容失败:`, error);
      // 如果简化失败，返回原始标题
      const titleMatch = content.match(/# 第(\d+)天/);
      return titleMatch ? `Day ${dayNum}` : content.substring(0, 100);
    }
  };

  // 提取每天的内容并转换为 Markdown 格式
  const extractDailyContentToMarkdown = (content: string): string => {
    try {
      // 检查内容是否已经是 Markdown 格式
      const isMarkdown =
        content.includes("# 第") ||
        content.includes("## ") ||
        content.includes("| ");

      if (isMarkdown) {
        let extractedContent = "";
        let searchIndex = 0;
        let dayIndex = 1;

        while (true) {
          // 查找当前天数的标题
          const dayPattern = `# 第${dayIndex}天`;
          const dayStartIndex = content.indexOf(dayPattern, searchIndex);

          if (dayStartIndex === -1) {
            break;
          }

          // 查找下一天的开始位置
          const nextDayPattern = `# 第${dayIndex + 1}天`;
          let dayEndIndex = content.indexOf(
            nextDayPattern,
            dayStartIndex + dayPattern.length,
          );

          // 如果没有下一天，查找其他可能的结束标识
          if (dayEndIndex === -1) {
            const endPatterns = [
              "\n## 住宿推荐",
              "\n## 费用明细",
              "\n## 注意事项",
              "\n## 总结",
              "\n# 住宿推荐",
              "\n# 费用明细",
              "\n# 注意事项",
              "\n# 总结",
            ];

            for (const pattern of endPatterns) {
              const found = content.indexOf(pattern, dayStartIndex);
              if (found !== -1 && (dayEndIndex === -1 || found < dayEndIndex)) {
                dayEndIndex = found;
              }
            }

            // 如果还没找到结束位置，使用文档末尾
            if (dayEndIndex === -1) {
              dayEndIndex = content.length;
            }
          }

          // 提取当前天的内容，但只保留第一个二级标题，并简化格式
          let dayContent = content.substring(dayStartIndex, dayEndIndex).trim();

          // 查找第一个二级标题的位置
          const firstH2Match = dayContent.match(/\n## ([^\n]+)/);
          if (firstH2Match) {
            const firstH2Index = dayContent.indexOf(firstH2Match[0]);
            const firstH2EndIndex = firstH2Index + firstH2Match[0].length;

            // 查找第二个二级标题的位置
            const secondH2Match = dayContent
              .substring(firstH2EndIndex)
              .match(/\n## ([^\n]+)/);
            if (secondH2Match) {
              const secondH2Index =
                firstH2EndIndex +
                dayContent.substring(firstH2EndIndex).indexOf(secondH2Match[0]);
              // 只保留到第二个二级标题之前的内容
              dayContent = dayContent.substring(0, secondH2Index).trim();
            }
            // 如果没有第二个二级标题，保留全部内容
          }

          // 简化内容格式，压缩字符数
          dayContent = simplifyContent(dayContent, dayIndex);

          // 如果不是第一天，添加分隔符
          if (dayIndex > 1) {
            extractedContent += "\n\n";
          }

          // 添加当天内容
          extractedContent += dayContent;

          // 准备下一次循环
          searchIndex = dayEndIndex;
          dayIndex++;

          // 安全措施：避免无限循环
          if (dayIndex > 10) {
            break;
          }
        }

        if (extractedContent) {
          return extractedContent;
        } else {
          return content.substring(0, 1000).trim();
        }
      }

      // 如果是 HTML 格式，进行解析
      let markdown = "";

      // 分割每天的内容 - 使用兼容的正则表达式
      const dayRegex = /<h1[^>]*>(.*?)<\/h1>(.*?)(?=<h1|$)/g;

      let dayMatch;
      let matchCount = 0;

      while ((dayMatch = dayRegex.exec(content)) !== null) {
        matchCount++;

        const dayTitle = dayMatch[1].replace(/<[^>]*>/g, "").trim();
        const dayContent = dayMatch[2];

        markdown += `## ${dayTitle}\n\n`;

        // 提取子标题 (h2)
        const h2Regex = /<h2[^>]*>(.*?)<\/h2>/g;
        let h2Match;
        let h2Count = 0;

        while ((h2Match = h2Regex.exec(dayContent)) !== null) {
          h2Count++;
          const h2Title = h2Match[1].replace(/<[^>]*>/g, "").trim();
          markdown += `### ${h2Title}\n\n`;

          // 获取这个h2后面的内容，直到下一个h2或结束
          const nextH2Index = dayContent.indexOf(
            "<h2",
            h2Match.index + h2Match[0].length,
          );
          const sectionContent = dayContent.substring(
            h2Match.index + h2Match[0].length,
            nextH2Index === -1 ? dayContent.length : nextH2Index,
          );

          // 处理表格
          const tableRegex = /<table[^>]*>(.*?)<\/table>/g;
          let tableMatch;
          let tableCount = 0;

          while ((tableMatch = tableRegex.exec(sectionContent)) !== null) {
            tableCount++;
            const tableMarkdown = parseTableToMarkdown(tableMatch[0]);
            markdown += tableMarkdown;
            markdown += "\n\n";
          }

          // 处理段落
          const pRegex = /<p[^>]*>(.*?)<\/p>/g;
          let pMatch;
          let pCount = 0;
          while ((pMatch = pRegex.exec(sectionContent)) !== null) {
            pCount++;
            const text = pMatch[1].replace(/<[^>]*>/g, "").trim();
            if (text) {
              markdown += `${text}\n\n`;
            }
          }
        }

        if (h2Count === 0) {
          // 如果没有 H2 标题，直接处理内容
          const pRegex = /<p[^>]*>(.*?)<\/p>/g;
          let pMatch;
          while ((pMatch = pRegex.exec(dayContent)) !== null) {
            const text = pMatch[1].replace(/<[^>]*>/g, "").trim();
            if (text) {
              markdown += `${text}\n\n`;
            }
          }
        }

        markdown += "\n---\n\n";
      }

      // 如果没有匹配到任何内容，可能不是标准的 HTML 格式
      if (matchCount === 0) {
        // 移除所有 HTML 标签，保留纯文本
        const cleanText = content.replace(/<[^>]*>/g, "").trim();
        return cleanText;
      }

      return markdown.trim();
    } catch (error) {
      console.error("提取内容失败:", error);
      // 如果解析失败，返回纯文本
      const fallback = content.replace(/<[^>]*>/g, "").trim();
      return fallback;
    }
  };

  // 解析表格为 Markdown
  const parseTableToMarkdown = (tableHtml: string): string => {
    try {
      let markdown = "";

      // 提取表头
      const theadRegex = /<thead[^>]*>(.*?)<\/thead>/;
      const theadMatch = theadRegex.exec(tableHtml);

      if (theadMatch) {
        const headerRowRegex = /<tr[^>]*>(.*?)<\/tr>/;
        const headerRowMatch = headerRowRegex.exec(theadMatch[1]);

        if (headerRowMatch) {
          const thRegex = /<th[^>]*>(.*?)<\/th>/g;
          const headers = [];
          let thMatch;

          while ((thMatch = thRegex.exec(headerRowMatch[1])) !== null) {
            const header = thMatch[1].replace(/<[^>]*>/g, "").trim();
            headers.push(header);
          }

          if (headers.length > 0) {
            markdown += "| " + headers.join(" | ") + " |\n";
            markdown += "| " + headers.map(() => "---").join(" | ") + " |\n";
          }
        }
      }

      // 提取表体
      const tbodyRegex = /<tbody[^>]*>(.*?)<\/tbody>/;
      const tbodyMatch = tbodyRegex.exec(tableHtml);

      if (tbodyMatch) {
        const rowRegex = /<tr[^>]*>(.*?)<\/tr>/g;
        let rowMatch;
        let rowCount = 0;

        while ((rowMatch = rowRegex.exec(tbodyMatch[1])) !== null) {
          rowCount++;

          const tdRegex = /<td[^>]*>(.*?)<\/td>/g;
          const cells = [];
          let tdMatch;

          while ((tdMatch = tdRegex.exec(rowMatch[1])) !== null) {
            const cell = tdMatch[1].replace(/<[^>]*>/g, "").trim();
            cells.push(cell);
          }

          if (cells.length > 0) {
            const rowMarkdown = "| " + cells.join(" | ") + " |\n";
            markdown += rowMarkdown;
          }
        }
      }

      return markdown;
    } catch (error) {
      console.error("解析表格失败:", error);
      return "";
    }
  };

  // 将 Markdown 转换为 HTML (使用 markdown-it)
  const markdownToHtml = (markdown: string): string => {
    try {
      // 初始化 markdown-it
      const md = new MarkdownIt({
        html: true, // 启用HTML标签
        breaks: true, // 自动换行
        linkify: true, // 自动链接
        typographer: true, // 启用排版规则
      });

      // 转换 Markdown 为 HTML
      const html = md.render(markdown);

      return html;
    } catch (error) {
      console.error("Markdown 转 HTML 失败:", error);
      // 如果转换失败，返回简单的HTML包装
      return `<div>${markdown.replace(/\n/g, "<br>")}</div>`;
    }
  };

  // 提交保存
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      setLoading(true);

      // 将原始HTML内容（实际是Markdown）转换为HTML作为pageDiv
      const convertedHtml = markdownToHtml(htmlContent);

      const submitData: CreateContentRequest = {
        city: values.city,
        title: values.title,
        pageDiv: convertedHtml, // 使用转换后的HTML
        content: values.content, // 保持原始Markdown内容
        durationDays: values.durationDays,
        tags: values.tags || [],
      };

      const result = await createContent(submitData);
      message.success(t('saveContentModal.saveSuccess'));

      // 使用返回数据中的 data.id 作为 productId
      const productId = result.data?.id || result.id || "1";
      onSuccess(productId);
    } catch (error) {
      console.error("保存失败:", error);
      message.error(t('saveContentModal.saveFailed'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={t('saveContentModal.title')}
      open={visible}
      onCancel={onCancel}
      width={800}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          {t('saveContentModal.cancel')}
        </Button>,
        <Button
          key="ai"
          type="default"
          loading={aiGenerating}
          onClick={generateContentWithAI}
        >
          {t('saveContentModal.aiSmartFill')}
        </Button>,
        <Button
          key="submit"
          type="primary"
          loading={loading}
          onClick={handleSubmit}
        >
          {t('saveContentModal.saveGuide')}
        </Button>,
      ]}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          city: "",
          title: "",
          content: "",
          durationDays: 1,
          tags: [],
        }}
      >
        <Form.Item
          label={t('saveContentModal.departureCity')}
          name="city"
          rules={[{ required: true, message: t('saveContentModal.departureCity.required') }]}
        >
          <Input placeholder={t('saveContentModal.departureCity.placeholder')} />
        </Form.Item>

        <Form.Item
          label={t('saveContentModal.guideTitle')}
          name="title"
          rules={[{ required: true, message: t('saveContentModal.guideTitle.required') }]}
        >
          <Input placeholder={t('saveContentModal.guideTitle.placeholder')} />
        </Form.Item>

        <Form.Item
          label={t('saveContentModal.guideContent')}
          name="content"
          rules={[{ required: true, message: t('saveContentModal.guideContent.required') }]}
        >
          <TextArea
            rows={12}
            placeholder={t('saveContentModal.guideContent.placeholder')}
          />
        </Form.Item>

        <Form.Item
          label={t('saveContentModal.guideDays')}
          name="durationDays"
          rules={[{ required: true, message: t('saveContentModal.guideDays.required') }]}
        >
          <InputNumber
            min={1}
            placeholder={t('saveContentModal.guideDays.placeholder')}
            style={{ width: "100%" }}
          />
        </Form.Item>

        <Form.Item
          label={t('saveContentModal.attractionTags')}
          name="tags"
          rules={[{ required: true, message: t('saveContentModal.attractionTags.required') }]}
        >
          <Select
            mode="tags"
            placeholder={t('saveContentModal.attractionTags.placeholder')}
            style={{ width: "100%" }}
          ></Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SaveContentModal;
